// miniprogram/pages/history/history.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    datasource: [],
    isLong:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var history = wx.getStorageSync('history') ? JSON.parse(wx.getStorageSync('history')) : ''
    var datasource = []
    if (history) {
      for (var i = 0; i < history.length; i++) {
        var item = history[i]
        datasource.push(JSON.parse(item))
      }

    }

    this.setData({
      datasource: datasource
    })
  },
  tap(e) {
    if (this.data.isLong) {
      return
    }

    const item = e.currentTarget.dataset.item
    var link = item.link
    var history = wx.getStorageSync('history')
    var datasource = []
    if (history) {
      datasource = JSON.parse(history)
    }
    var itemStr = JSON.stringify(item)
    var count = datasource.indexOf(itemStr)
    if (count != -1) {
      datasource.splice(count, 1)
    }
    datasource.splice(0, 0, itemStr)

    wx.setStorageSync('history', JSON.stringify(datasource))

    wx.navigateTo({
      url: '../section/section?link=' + item.link,
    })
  },

  long(e) {
    this.setData({
      isLong:true
    })
    var that = this
    wx.showModal({
      title: '提示',
      content: '是否删除当前记录?',
      success(res) {
        if (res.confirm) {
          const item = e.currentTarget.dataset.item
          var link = item.link
          var history = wx.getStorageSync('history')
          var datasource = []
          if (history) {
            datasource = JSON.parse(history)
          }
          var itemStr = JSON.stringify(item)
          var count = datasource.indexOf(itemStr)
          if (count != -1) {
            datasource.splice(count, 1)
          }

          wx.setStorageSync('history', JSON.stringify(datasource))
          that.onShow()
          that.setData({
            isLong : false
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
          that.setData({
            isLong: false
          })
        }
      }

    })

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})